/*
 SAMPLE FORM
*/
//var qs = require('querystring');
var Discussions_Impl = require('.././core/Discussions_Impl');
require('./common');
/*
 *
 *
 *
 *
 *
 */
    var gs3 = require('gs3');
    var Database = gs3.Models.Database;
    var Entity = gs3.Models.Entity;
    var db = new Database(config, true);


/* Save and return created post
 *
 * (Type of Post)
 * A (rTP=1) reply to Post= to post
 * B (rTCP=2) reply to the comment of post
 * C (aP=3) announcePost for the new announcement
 * 
 */
    exports.save = function(req, res){
	var type = req.params.postType; // Type of Post
	var value = req.params.value; // comment or announcement
	var dateTime = req.params.date; // Date Time
	var id = req.params.companyID; // Company ID/Announcement ID for viewing
	if(type=="3"){
	    /* Add Post Announcement */
		var userID = "10"; // Sample User ID
		// Announcement save to the database functions
		addAnnouncement("",value,id,type,dateTime,userID, function(announcementID){
		    res.send(getannouncement(announcementID,value,id,type,dateTime,userID,""));
		});
		//var announcementID = "1"; // Sample Announcement ID
		    
		//announcementID++;
		userID++;
	}else{
	    if(type=="1"){
		/* Add Comment */
		var userID = "10"; // Sample User ID
		// Announcement save to the database functions
		addComment(commentID,id,value,type,dateTime,userID);
		var commentID = "1"; // Sample Announcement ID
		    res.send(getComment(commentID,id,value,type,dateTime,userID));
		commentID++;
		userID++;
	    }else{
		// Adding comment to a comment on post
		if(type=="2"){
		    /* Add Comment */
		    var userID = "15"; // Sample User ID
		    // Announcement save to the database functions
		    addComment(commentID,id,value,type,dateTime,userID);
		    var commentID = "1"; // Sample Announcement ID
			//res.send(getComment(commentID,id,value,type,dateTime,userID));
			res.send(addCommentToPost(commentID,dateTime,value));
		    commentID++;
		    userID++;
		}
	    }
	}
    }
    
/*----------------------------- TO DATABASE ---------------------------------------------------------*/
// Announcement save to the database functions (SAVE)
function addAnnouncement(announcementID,post,companyID,type,dateTime,userID,callback){
    var announcementPost = new Entity('tbannouncement', 'id');

    announcementPost.fields.company_id = companyID;
    announcementPost.fields.user_id = userID;
    announcementPost.fields.announcement = post;
    announcementPost.fields.type = type;
    announcementPost.fields.is_active = "1";
    announcementPost.fields.date = dateTime;
    
    db.insert(announcementPost, function(err, data) {
	    if(err){
		//res.send(err.message);
		console.log(err.message)
	    }else{
		id = data.insertId; // Announcement ID
		callback(id);
		console.log(id)
	    }
    });
}
// new Comment save to database functions
function addComment(commentID,announcementID,comment,type,dateTime,userID){
    var strSQL = "INSERT INTO tbcomment (user_id,comment,date,announcement_id,type,is_active) VALUES ('" + userID + "','"+comment+"','"+dateTime+"','"+announcementID+"','"+type+"','1')"
    
    if(comment != "undefined"){
            conn.query(strSQL);
            console.log("done adding comment...")
    }
}
function dateTimeDate(postDate){
    var d = new Date(postDate); 
    return d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2) + ' ' + d.getHours() + ':' + ('0' + d.getMinutes()).slice(-2) + ':' + ('0' + d.getSeconds()).slice(-2);
}
/*----------------------------- GET Load Data ---------------------------------------------------------*/
// Load announcement from the database (GET)
exports.getAnnouncement = function(req, res){
    Discussions_Impl.getAllPostWithComments('10', ' ORDER BY id DESC', function(err, data) {
        if (err) {
            res.send(err.message);
        } else {
            var output = "";
            for (var key=0;key<data.length;key++) {
                announcementID = data[key].id+"";
                announcement = data[key].announcement;
                companyID = data[key].company_id+"";
                type = data[key].type+"";
                dateTime = dateTimeDate(data[key].date);
                userID = data[key].user_id+"";
		
		if (data[key].tbcomment) {
		    output += getannouncement(announcementID,announcement,companyID,type,dateTime,userID,data[key].tbcomment);
		}
		
	    }
		
            res.send(output);
        }
    });
    
}

// Load comment from the database
exports.getCommenttoDB = function(req, res){
    var output="";
    var strSQL = "SELECT * FROM tbcomment WHERE type='1' ORDER BY id ASC";
    conn.query(strSQL, function(err, results, fields){
            if(err) throw err;
            for (var index in results) {
		commentID = results[index].id;
		announcementID = results[index].announcement_id;
		newComment = results[index].comment;
		type = results[index].type;
		dateTime = results[index].date;
		userID = results[index].user_id;
		postDate = dateTimeDate(dateTime);
		    output += getComment(commentID,announcementID,newComment,type,postDate,userID);
            }
            res.send(output);
    });
}
// Load comment of comment
exports.getCommentofComment = function(req, res){
    var output="";
    var strSQL = "SELECT * FROM tbcomment WHERE type='2' ORDER BY id ASC";
    conn.query(strSQL, function(err, results, fields){
            if(err) throw err;
            for (var index in results) {
		commentID = results[index].id;
		announcementID = results[index].announcement_id;
		newComment = results[index].comment;
		type = results[index].type;
		dateTime = results[index].date;
		userID = results[index].user_id;
		postDate = dateTimeDate(dateTime);
		    output += addCommentToPost(commentID,dateTime,newComment);
            }
            res.send(output);
    });
}
// Delete selected announcement to delete
exports.destroy = function (req, res) {
    var id = req.params.announcement_id;
    var action = req.params.action;
    if(action=="deletePost"){
      conn.query('DELETE FROM tbannouncement WHERE id="'+id+'"');
      conn.query('DELETE FROM tbcomment WHERE announcement_id="'+id+'"');
      res.send("Announcement was successfully deleted.");
    }else{
	if(action=="deleteComment"){
	    conn.query('DELETE FROM tbcomment WHERE id="'+id+'"');
	    res.send("Selected comment was successfully deleted.");
	}
    }
}

/*----------------------------- FUNCTIONS ---------------------------------------------------------*/
/* For Posting Announcement
 * function name getannouncement()
 *
 * Parameters on the functions
 * 	@announcementID - get the announcement/post id from the database
 * 	@announcement - the value or the post of the user
 * 	@companyID - for viewing of the current member of the company
 * 	@type - type of post (1,2,3)
 * 	@dateTime - set the time for the post
 * 	@userID - get user id who post/ create the post.
 *
 */
function getannouncement(announcementID,announcement,companyID,type,dateTime,userID,comments){
    var ret = '<li class="postContainerList" id="myPost_'+announcementID+'">';
	    ret +=  '<div>';
		ret +=  '<img src="images/avatar/avatar.png" width="60" height="55"/>';
	    ret +=  '</div>';
	    ret +=  '<div>';
		ret +=  '<p>';
		    ret +=  '<label class="postlblN"> '+userID+' </label>';
			ret += 	'<br>';
			ret +=  '<label class="postlblC">';
			    ret +=  announcement;
			ret +=  '</label>';
			ret +=  '<br>';
			ret +=  '<label class="postlblA">';
				ret +=  '<icon class="icon-time"></icon>&nbsp;';
				ret +=	'<label class="timeago" title="'+dateTime+'"> </label>';
			ret +=  '</label>';
			ret +=  '<label class="postlblActions showReply" data-announcement-id="'+announcementID+'"  data-action-post-type="rTP"> Reply  </label>';
			ret +=  '<label class="pull-right postlblActions deletePost" data-action="deletePost"  data-announcement-id="'+announcementID+'"> Delete  </label>';
			ret +=  '<div class="hr"></div>';
		ret +=  '</p>';
		// Append new comment created
		ret += 	'<div class="appendNewComment" id="appendNewComment_'+announcementID+'_rTP"></div>';
		//Comment view
		/*-----------------------------*/
		for (var i in comments) {
		    commentID = comments[i].id;
		    announcementID = comments[i].announcement_id;
		    newComment = comments[i].comment;
		    type = comments[i].type;
		    dateTime = dateTimeDate(comments[i].date);
		    userID = comments[i].user_id;
			ret += getComment(commentID,announcementID,newComment,type,dateTime,userID);
		}//commentID,announcementID,newComment,type,dateTime,userID
		// Comment Reply
		ret +=  '<div class="commentAction display" id="showReply_'+announcementID+'_rTP">';
			ret +=  '<div>';
				ret +=  '<img src="images/avatar/avatar.png" width="35" height="35" style="border:2px solid #ddd;"/>';
			ret +=  '</div>';
			ret +=  '<div>';
				ret +=  '<textarea class="input-medium commentBox" id="newComment_'+announcementID+'_'+'rTP"></textarea>';
				ret +=  '<input type="button" class="button-icon commentbtn addButtonComment" data-action-post-type="rTP" data-announcement-id="'+announcementID+'" value="Send" />';
			ret +=  '</div>';
		ret +=  '</div>';		
	ret +=  '</div>';
ret += '</li>';
    
    return ret;
}
/* For Commenting on the post
 * function name getannouncement()
 *
 * Parameters on the functions
 * 	@commentID - get the comment id from the database
 * 	@newComment - the value or the post of the user in the comment
 * 	@type - type of post (1,2,3)
 * 	@dateTime - set the time for the post
 * 	@userID - get user id who post/ create the post.
 *
 */
function getComment(commentID,announcementID,newComment,type,dateTime,userID){
	var ret =  '<div class="commentReply" id="deleteComment_'+commentID+'">';
		ret +=  '<div>';
			ret +=  '<img src="images/avatar/avatar.png" width="35" height="35" style="border:2px solid #ddd;"/>';
		ret +=  '</div>';
		ret +=  '<div>';
			ret +=  '<p>';
				ret +=  '<label class="postlblN"> '+userID+' </label>';
				ret +=  '<br>';
				ret +=  '<label class="postlblC">'+newComment+'</label>';
				ret +=  '<br>';
				ret +=  '<label class="postlblA">';
					ret +=  '<icon class="icon-time"></icon>&nbsp;';
					ret +=  '<label class="timeago" title="'+dateTime+'"> </label>';
				ret +=  '</label>';
				ret +=  '<label class="postlblActions showReply" data-comment-id="'+commentID+'" data-action-post-type="rTCP"> Reply </label>';
				ret +=  '<label class="pull-right postlblActions deleteNewComment" data-comment-id="'+commentID+'" data-action="deleteComment"> Delete </label>';
				ret +=  '<div class="hr"></div>';
			ret +=  '</p>';
			// Comment to a post reply view
			ret += 	'<div class="appendNewComment appendCommentofComment" id="appendNewComment_'+commentID+'_rTCP"></div>';
			// View of the Reply to the comment of post
			/* ----------------------- */
			// Reply to the comment of post
			ret +=  '<div class="commentPostAction display showReply" id="showReply_'+commentID+'_rTCP">';
				ret +=  '<div>';
					ret +=  '<img src="images/avatar/avatar.png" width="35" height="35" style="border:2px solid #ddd;"/>';
				ret +=  '</div>';
				ret +=  '<div>';
					ret +=  '<textarea class="input-medium commentBox" id="newComment_'+commentID+'_rTCP"></textarea>';
					ret +=  '<input type="button" class="button-icon addButtonComment commentbtn" data-action-post-type="rTCP" data-comment-id="'+commentID+'" value="Send" />';
				ret +=  '</div>';
				ret +=  '<div class="hr" style="width:505px;"></div>';
			ret +=  '</div>';
		ret +=  '</div>';
    ret +=  '</div>';
	return ret;
}
// Comment of comment on post
function addCommentToPost(commentID,dateTime,newComment){
    var ret =  '<div class="commentPostReply">';
	    ret +=  '<div>';
		    ret +=  '<img src="images/avatar/avatar.png" width="35" height="35" style="border:2px solid #ddd;"/>';
	    ret +=  '</div>';
	    ret +=  '<div>';
		    ret +=  '<p>';
			    ret +=  '<label class="postlblN"> Samuel G. Pulta </label>';
			    ret +=  '<br>';
			    ret +=  '<label class="postlblC">'+newComment+'</label>';
			    ret +=  '<br>';
			    ret +=  '<label class="postlblA">';
				ret +=  '<icon class="icon-time"></icon>&nbsp;';  
				ret +=  '<label class="timeago" title="'+dateTime+'"> </label>';
			    ret +=  '</label>';
			    ret +=  '<label class="pull-right postlblActions"> Delete </label>';
			    ret +=  '<div class="hr"></div>';
		    ret +=  '</p>';
	    ret +=  '</div>';
    ret +=  '</div>';
    return ret;

}